package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //1 paramMap转化成实体
        String depJson = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(depJson, Department.class);
        //2 拿医院编码、科室编码到mongo查询科室信息
        Department departmentExist = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(),
                        department.getDepcode());

        if(departmentExist!=null){
            //3 有进行更新
            department.setId(departmentExist.getId());
            department.setCreateTime(departmentExist.getCreateTime());
            department.setIsDeleted(0);
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        }else{
            //4 没有进行新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }

    }

    //获取分页列表
    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //1分页实现
        //1.1创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //1.2分页查询对象，0是第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        //2创建条件筛选对象
        //2.1创建查询条件对象
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);
        //2.2创建筛选条件构造器
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Example<Department> example = Example.of(department,matcher);

        Page<Department> departmentPage = departmentRepository.findAll(example, pageable);
        return departmentPage;
    }

    //删除科室
    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository
                .getDepartmentByHoscodeAndDepcode(hoscode,
                        depcode);
        if(department==null){
            throw new YyghException(20001,"科室不存在");
        }
        departmentRepository.deleteById(department.getId());
    }

    //查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //0创建返回对象
        List<DepartmentVo>  result = new ArrayList<>();
        //1根据hoscode查询所有科室信息
        //1.1创建对象存入筛选条件
        Department department = new Department();
        department.setHoscode(hoscode);
        //1.2创建模板设置筛选条件
        Example<Department> example = Example.of(department);
        //1，3调接口查询
        List<Department> departmentList = departmentRepository.findAll(example);
        //2 根据bigcode进行数据整合（进行数据分组）
        //Map<String, List<Department>>   key = Bigcode , value= 分组的小科室信息
        Map<String, List<Department>> departmentMap
                = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //3 遍历相关对象
        for (Map.Entry<String, List<Department>> stringListEntry : departmentMap.entrySet()) {
            //4 封装大科室信息
            DepartmentVo bigDepVo = new DepartmentVo();
            bigDepVo.setDepcode(stringListEntry.getKey());
            bigDepVo.setDepname(stringListEntry.getValue().get(0).getBigname());
            //5 封装小科室信息
            //5.1封装小科室集合
            List<DepartmentVo> depVoList = new  ArrayList<>();
            //5.2 获取查询到小科室信息
            List<Department>  depList = stringListEntry.getValue();
            //5.5遍历封装小科室
            for (Department depInfo : depList) {
                DepartmentVo departmentVo = new DepartmentVo();
                BeanUtils.copyProperties(depInfo,departmentVo);
                depVoList.add(departmentVo);
            }
            //5.6小科室集合存入大科室对象
            bigDepVo.setChildren(depVoList);
            //6大科室信息存入集合
            result.add(bigDepVo);
        }
        return result;
    }

    //设置科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository
                .getDepartmentByHoscodeAndDepcode(hoscode,
                        depcode);
        if(department==null){
            throw  new YyghException(20001,"科室信息有误");
        }
        return department.getDepname();
    }

    //根据医院编码、科室编码获取科室信息
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository
                .getDepartmentByHoscodeAndDepcode(hoscode,
                        depcode);
        return department;
    }


}
